package cn.bby.query.server.domain.service.fetcher;

import cn.bby.jtk.base.constant.CommonErrorCode;
import cn.bby.jtk.base.exception.ServiceException;
import cn.bby.jtk.web.CommonResult;
import cn.bby.query.base.constant.AdvQueryErrorCode;
import cn.bby.query.base.model.req.QueryRequest;
import cn.bby.query.base.model.req.QueryResponse;
import cn.bby.query.base.util.UriUtil;
import cn.bby.query.server.domain.agg.metadata.entity.InterfaceInfo;
import cn.bby.query.server.domain.service.manager.DataStorageManager;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;

import java.util.function.Consumer;

/**
 * @author ben
 * @since 2025/4/20 00:29
 */
public abstract class BaseDataFetcherImpl implements DataFetcher {
    protected int pageSize = 200;
    @Resource
    protected ObjectMapper objectMapper;
    @Resource
    protected DataStorageManager dataStorageManager;

    protected void doRequest(InterfaceInfo interfaceInfo, QueryRequest queryRequest, Consumer<QueryResponse<JSONObject>> callback) {
        HttpRequest post = HttpUtil.createPost(UriUtil.concatUri(interfaceInfo.getBaseUrl(), interfaceInfo.getMethodPath()));
        post.body(JSONUtil.toJsonStr(queryRequest));
        post.contentType(ContentType.JSON.getValue());
        post.timeout(60000);

        try (HttpResponse response = post.execute()) {
            if (!response.isOk()) {
                throw new ServiceException(AdvQueryErrorCode.HTTP_REQ_ERROR, "接口请求失败：" + response);
            }
            CommonResult<QueryResponse<JSONObject>> res = objectMapper.readValue(response.body(), new TypeReference<>() {
            });
            if (!CommonErrorCode.SUCCESS.equals(res.getCode()) || res.getData() == null) {
                throw new ServiceException(CommonErrorCode.SYSTEM_ERROR, "接口返回值错误:" + res);
            }
            callback.accept(res.getData());
        } catch (JsonProcessingException e) {
            throw new ServiceException(CommonErrorCode.SYSTEM_ERROR, e);
        }
    }
}
